package com.zhenghaijin.service;

import com.zhenghaijin.dto.UserDTO;
import com.zhenghaijin.model.User;
import com.zhenghaijin.repository.UserRepository;
import com.zhenghaijin.security.JwtTokenProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenProvider jwtTokenProvider;

    // Constructor injection
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtTokenProvider jwtTokenProvider) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.jwtTokenProvider = jwtTokenProvider;
    }

    public User register(UserDTO userDTO) {
        // 新增重复性校验
        if (userRepository.findByUsername(userDTO.getUsername()) != null) {
            throw new IllegalArgumentException("用户名已存在：Username already exists");
        }
        if (userRepository.findByEmail(userDTO.getEmail()) != null) {
            throw new IllegalArgumentException("邮箱已经注册：Email already registered");
        }

        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        user.setEmail(userDTO.getEmail());
        user.setRole("USER");
        
        User savedUser = userRepository.save(user);
        System.out.println("用户注册成功，ID：" + savedUser.getId());
        return savedUser; // 返回保存后的用户对象
    }



    public String login(UserDTO userDTO) {
        User user = userRepository.findByUsername(userDTO.getUsername());
        if (user != null && passwordEncoder.matches(userDTO.getPassword(), user.getPassword())) {
            return jwtTokenProvider.createToken(user.getUsername(), user.getRole());
        }
        throw new BadCredentialsException("错误的用户名或密码：Invalid username or password");
    }


}
